package com.zrrd.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.gmall.model.product.BaseAttrInfo;
import com.zrrd.gmall.model.product.BaseAttrValue;
import com.zrrd.gmall.product.mapper.BaseAttrInfoMapper;
import com.zrrd.gmall.product.mapper.BaseAttrValueMapper;
import com.zrrd.gmall.product.service.BaseAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseAttrServiceImpl  implements BaseAttrService {
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        List<BaseAttrInfo> infoList = baseAttrInfoMapper.getAttrInfoList(category1Id, category2Id, category3Id);
        return infoList;
    }

    @Override
    @Transactional
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //如果id为空-》添加
        if (baseAttrInfo.getId() == null){
            //将传递的数据添加到平台属性表
            baseAttrInfoMapper.insert(baseAttrInfo);

        }else {
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //要先删除原本的属性值
        QueryWrapper<BaseAttrValue> wrapper =new QueryWrapper<>();
        wrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(wrapper);

        //获取传来的属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            //因为没有批量添加而使用如下方法
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }
    //根据属性id获取属性集合
    @Override
    public List<BaseAttrValue> getAttrInfo(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper =new QueryWrapper<>();
        wrapper.eq("attr_id",attrId);
        List<BaseAttrValue> baseAttrValues = baseAttrValueMapper.selectList(wrapper);
        return baseAttrValues;
    }

}
